package com.app.bimo.commonbusiness.util;

/**
 * Created by limo on 16/3/1.
 */

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.collection.ArrayMap;

import static android.app.Notification.EXTRA_CHANNEL_ID;
import static android.content.Context.CLIPBOARD_SERVICE;
import static android.provider.Settings.EXTRA_APP_PACKAGE;


public class SystemUtil {

//    /**
//     * 获取设备信息
//     *
//     * @return
//     */
//    public static ArrayMap<String, String> getPhoneInfo(WogaBaseActivity activity) {
//
//        ArrayMap<String, String> infoChildMap = new ArrayMap<String, String>();
//        if (activity != null) {
//
//        }
//        TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
//        infoChildMap.put("type", "login");
//        PackageInfo info = getPackageInfo(activity);
//
//
//        String _imsi = null;
//        try {
//            _imsi = tm.getSubscriberId();
//        } catch (Exception e) {
//            _imsi = "未知";
//        }
//
//        if (info != null) {
//            infoChildMap.put("app_ver", info.versionName);
//            infoChildMap.put("app_ver", info.versionName);
//            infoChildMap.put("versioncode", info.versionCode + "");
//            infoChildMap.put("package_name", info.packageName);
//        }
//        infoChildMap.put("model", android.os.Build.MODEL);
//        infoChildMap.put("os", "2");
//        infoChildMap.put("sys_ver", android.os.Build.VERSION.RELEASE);
//        infoChildMap.put("channel", getAppMetaData(activity, "UMENG_CHANNEL"));
//        infoChildMap.put("device_id", tm.getDeviceId());
//        infoChildMap.put("imsi", _imsi);
//        infoChildMap.put("imei", tm.getSimSerialNumber());
//        infoChildMap.put("network", String.valueOf(getNetWorkType(activity)));
//        infoChildMap.put("remark", getOperatorName(activity));
//        return infoChildMap;
//    }

//    /**
//     * 获取手机IMEI
//     *
//     * @param context
//     * @return
//     */
//    public static final String getIMEI(Context context) {
//        try {
//            //实例化TelephonyManager对象
//            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//            //获取IMEI号
//            String imei =telephonyManager.getImei();
//            //在次做个验证，也不是什么时候都能获取到的啊
//            if (imei == null) {
//                imei = "test";
//            }
//            return imei;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "test";
//        }
//
//    }

    /**
     * 获取手机唯一标识符
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        try {
            return toMD5(id);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return id;
        }
    }

    private static String toMD5(String text) throws NoSuchAlgorithmException {
        //获取摘要器 MessageDigest
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        //通过摘要器对字符串的二进制字节数组进行hash计算
        byte[] digest = messageDigest.digest(text.getBytes());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            //循环每个字符 将计算结果转化为正整数;
            int digestInt = digest[i] & 0xff;
            //将10进制转化为较短的16进制
            String hexString = Integer.toHexString(digestInt);
            //转化结果如果是个位数会省略0,因此判断并补0
            if (hexString.length() < 2) {
                sb.append(0);
            }
            //将循环结果添加到缓冲区
            sb.append(hexString);
        }
        //返回整个结果
        return sb.toString();
    }


    /**
     * 获取手机品牌
     *
     * @return
     */
    public static String getPhoneBrand() {
//        return android.os.Build.BRAND;
        return Build.MODEL;
    }

    /**
     * 图片是79时的图片宽度
     *
     * @param context
     * @return
     */
    public static final int getImgW99(Context context) {
//        int w = SystemUtil.getWidth(context) * 99 / 375;
        int w = getImgW97(context) * 99 / 122;
        return w;

    }

    /**
     * 图片是45时的图片宽度
     *
     * @param context
     * @return
     */
    public static final int getImgW45(Context context) {
//        int w = SystemUtil.getWidth(context) * 99 / 375;
        int w = getImgW97(context) * 65 / 122;
        return w;

    }


    public static final int getImgW189(Context context) {
//        int w = SystemUtil.getWidth(context) * 99 / 375;
        int w = getWidth(context) * 229 / 375;
        return w;

    }

    /**
     * 图片是63时的图片宽度
     *
     * @param context
     * @return
     */
    public static final int getImgW63(Context context) {
        int w = getImgW97(context) * 63 / 97;
        return w;

    } /**
     * 图片是63时的图片宽度
     *
     * @param context
     * @return
     */
    public static final int getImgW70(Context context) {
        int w = getImgW97(context) * 70 / 97;
        return w;

    } /**
     * 图片是63时的图片宽度
     *
     * @param context
     * @return
     */
    public static final int getImgW80(Context context) {
        int w = getImgW97(context) * 80 / 97;
        return w;

    }

    /**
     * 设计图图片是 97 时的图片宽度
     * 因为图片需要 上下左右阴影  所以要设置5dp的padding
     *
     * @param context
     * @return
     */
    public static final int getImgW97(Context context) {
        int w = SystemUtil.getWidth(context) - dip2px(context, 60);
        return w / 3;

    }

    /**
     * 获取字体
     *
     * @param context
     * @return
     */
    public static final Typeface getHeavyTypeface(Context context) {
        return Typeface.createFromAsset(context.getAssets(), "SourceHanSerifCN-Heavy.ttf");
    }

    /**
     * 获取字体
     *
     * @param context
     * @return
     */
    public static final Typeface getBoldTypeface(Context context) {
        return Typeface.createFromAsset(context.getAssets(), "SourceHanSerifCN-Bold.ttf");
//        return Typeface.createFromAsset(context.getAssets(), "SourceHanSerifCN-Heavy.ttf");
    }

    /**
     * 图片是51时的图片宽度
     *
     * @param context
     * @return
     */
    public static final int getImgW71(Context context) {
//        int w = SystemUtil.getWidth(context) * 99 / 375;
        int w = getImgW97(context) * 71 / 122;
        return w;

    }

    /**
     * 图片是51时的图片宽度
     *
     * @param context
     * @return
     */
    public static final int getImgW46(Context context) {
//        int w = SystemUtil.getWidth(context) * 99 / 375;
        int w = getImgW97(context) * 46 / 122;
        return w;

    }

    /**
     * 图片是84时的图片宽度
     *
     * @param context
     * @return
     */
    public static final int getImgW84(Context context) {
//        int w = SystemUtil.getWidth(context) * 99 / 375;
        int w = (getImgW97(context) * 84) / 109;
        return w;

    }

    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    public static PackageInfo getPackageInfo(Activity activity) {
        PackageManager manager = activity.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(activity.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return info;
    }

//    /**
//     * 获取网络状态，wifi,wap,2g,3g.
//     *
//     * @param context 上下文
//     * @return int 网络状态 {@link #},{@link #},
//     * *{@link #},{@link #}
//     * *<p>{@link #}
//     */
//    public static String getNetWorkType(Context context) {
//        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//        String mNetWorkType = "";
//        if (networkInfo != null && networkInfo.isConnected()) {
//            String type = networkInfo.getTypeName();
//            if (type.equalsIgnoreCase("WIFI")) {
//                mNetWorkType = "WIFI";
//            } else if (type.equalsIgnoreCase("MOBILE")) {
//                String proxyHost = android.net.Proxy.getDefaultHost();
//                mNetWorkType = TextUtils.isEmpty(proxyHost)
//                        ? isFastMobileNetwork(context)
//                        : "WAP";
//            }
//        } else {
//            mNetWorkType = "没有网络";
//        }
//        return mNetWorkType;
//    }

    /**
     * 获取网络类型
     *
     * @param context
     * @return
     */
    private static String isFastMobileNetwork(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        switch (telephonyManager.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return "2G"; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return "2G"; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return "2G"; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return "3G"; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return "3G"; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return "2G"; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return "3G"; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return "3G"; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return "3G"; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return "3G"; // ~ 400-7000 kbps
            case TelephonyManager.NETWORK_TYPE_EHRPD:
                return "3G"; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
                return "3G"; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return "3G"; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return "2G"; // ~25 kbps
            case TelephonyManager.NETWORK_TYPE_LTE:
                return "4G"; // ~ 10+ Mbps
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                return "";
            default:
                return "";
        }
    }

    /**
     * 获取运营商名称
     *
     * @param activity
     * @return
     */
    private static String getOperatorName(Activity activity) {
        TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = tm.getSimOperator();

        if (operator != null) {
            if (operator.equals("46000") || operator.equals("46002")) {
                return "中国移动";
            } else if (operator.equals("46001")) {
                return "中国联通";
            } else if (operator.equals("46003")) {
                return "中国电信";
            }
        }
        return null;
    }


    /**
     * 获取application中指定的meta-data
     *
     * @return 如果没有获取成功(没有对应值 ， 或者异常)，则返回值为空
     */
    public static String getAppMetaData(Context ctx, String key) {
        if (ctx == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(key);
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData;
    }

    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
//
//    /**
//     * 判断是否是wifi
//     * @param context
//     * @return
//     */
//    public static boolean isWifi(Context context) {
//        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//        NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//
//        if (!wifiNetInfo.isConnected()) {
//            return false;
//            //改变背景或者 处理网络的全局变量
//        } else {
//            //改变背景或者 处理网络的全局变量
//            return true;
//        }
//    }
//    /**
//     * 检查当前网络是否可用
//     *
//     * @param
//     * @return
//     */
//
//    public static boolean isNetworkAvailable(Context context) {
//        return NetWorkManager.getManager(context).isHaveNetwork();
//    }

    /**
     * 判断android SDK 版本是否大于等于5.0
     *
     * @return
     */
    public static boolean isAndroid5() {

        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    }

    public static int getWidtht(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        return (wm.getDefaultDisplay().getWidth() + dip2px(context, 6)) / 4;
    }

    public static int getHigh(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        return (wm.getDefaultDisplay().getHeight());
    }

    public static int getWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        return (wm.getDefaultDisplay().getWidth());
    }

    public static int getTimeLineLeftWidth(Context context) {
        return getWidth(context) - getTimeLineLeftDateWidth(context) - getTimeLineLeftStateWidth(context);
    }

    /**
     * 1. 从剪切板获得文字。
     */
    public static String getSysClipboardText(Context context) {
        String ret = "";
        ClipboardManager cm = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
        ClipData data = cm.getPrimaryClip();
        if (data == null) {
            return "";
        }
        ClipData.Item item = data.getItemAt(0);
        if (item != null) {
            if (item.getText() == null) {
                return "";
            }
            ret = item.getText().toString();
            //对剪贴板文字的操作
            if (ret.length() > 0) {
                if (ret.startsWith("bimo:")) {
                    return ret;
                } else {
                    return "";
                }
            } else {
                return "";
            }
        } else return "";
    }


    /**
     * 拿章节名称  渠道名称
     * "bimo:cnid=abc&nid=abc&chid=abc&pf=wechat";
     */
    public static ArrayMap<String, String> getClipboardTextMap(String s) {
        ArrayMap<String, String> map = new ArrayMap<>();
        s = s.substring(s.indexOf(":") + 1, s.length());
        String[] ms = s.split("&");
        if (ms == null) {
            return map;
        }
        for (int i = 0; i < ms.length; i++) {
            if ((ms[i].split("=").length > 1)) {
//                Log.e("aaa", "getClipboardTextMap: " + ms[i].split("=")[0] + "-----" + ms[i].split("=")[1]);
                map.put(ms[i].split("=")[0], ms[i].split("=")[1]);
            }
        }
        return map;
    }


    /**
     * 日期宽度
     *
     * @param context
     * @return
     */
    public static int getTimeLineLeftDateWidth(Context context) {
        return dip2px(context, 74);
    }

    /**
     * 左边线和点的宽度
     *
     * @param context
     * @return
     */
    public static int getTimeLineLeftStateWidth(Context context) {
        return dip2px(context, 17);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dp) {
        DisplayMetrics metrics = getDisplayMetrics(context);
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
    }

    /**
     * 获取书架页面头部高度
     */
    public static int getBookrackHeadHeight(Context context) {
        final float scale = getWidth(context) * 360 / 750;
        return (int) scale;
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 根据手机的分辨率PX(像素)转成DP
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics metrics = context
                .getResources()
                .getDisplayMetrics();
        return metrics;
    }


    public static int pxToDp(int px, Context context) {
        DisplayMetrics metrics = getDisplayMetrics(context);
        return (int) (px / metrics.density);
    }

    public static int spToPx(int sp, Context context) {
        DisplayMetrics metrics = getDisplayMetrics(context);
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, metrics);
    }

    public static int pxToSp(int px, Context context) {
        DisplayMetrics metrics = getDisplayMetrics(context);
        return (int) (px / metrics.scaledDensity);
    }


    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return bytesToHexString(digest.digest());
    }

    /**
     * byte  转string
     *
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    /**
     * 检查网络是否可用
     *
     * @param activity
     * @return
     */
    public static boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
//                    System.out.println(i + "===状态===" + networkInfo[i].getState());
//                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
//                    Log.i(TAG, "isNetworkAvailable: " + "===状态===" + networkInfo[i].getState() + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    public static boolean checkNet(Context context) {

        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {

                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {

                    if (info.isConnected()) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }

    }

    public static float getFontSize() {
        Configuration mCurConfig = new Configuration();
        return mCurConfig.fontScale;

    }


    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return 语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return Build.BRAND;
    }


    //获取输入法打开的状态
    public static void closeInput(Activity activity) {
        if (activity.getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
        } else {
            //如果仅仅是用来判断网络连接
            //则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    /* @author suncat
     * @category 判断是否有外网连接（普通方法不能判断外网的网络是否连接，比如连接上局域网）
     * @return
     */
    public static final boolean ping() {

        String result = null;
        try {
            String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("----result---", "result = " + result);
        }
        return false;
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 跳转到设置通知权限页面
     *
     * @param context
     */
    public static void gotoSettingNotify(Context context) {
        try {
            // 根据isOpened结果，判断是否需要提醒用户跳转AppInfo页面，去打开App通知权限
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            intent.putExtra(EXTRA_APP_PACKAGE, context.getPackageName());
            intent.putExtra(EXTRA_CHANNEL_ID, context.getApplicationInfo().uid);

            //这种方案适用于 API21——25，即 5.0——7.1 之间的版本可以使用
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);

            // 小米6 -MIUI9.6-8.0.0系统，是个特例，通知设置界面只能控制"允许使用通知圆点"——然而这个玩意并没有卵用，我想对雷布斯说：I'm not ok!!!
            //  if ("MI 6".equals(Build.MODEL)) {
            //      intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            //      Uri uri = Uri.fromParts("package", getPackageName(), null);
            //      intent.setData(uri);
            //      // intent.setAction("com.android.settings/.SubSettings");
            //  }
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            // 出现异常则跳转到应用设置界面：锤子坚果3——OC105 API25
            Intent intent = new Intent();
            //下面这种方案是直接跳转到当前应用的设置界面。
            //https://blog.csdn.net/ysy950803/article/details/71910806
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
            intent.setData(uri);
            context.startActivity(intent);
        }
    }

}

